package com.lanchetech.user.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanchetech.bean.request.TeacherGroupReq;
import com.lanchetech.bean.response.BasePageResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.bean.vo.TeacherGroupVO;
import com.lanchetech.dao.TeacherGroupMapper;
import com.lanchetech.entity.User;
import com.lanchetech.service.DaoService;
import com.lanchetech.user.service.TeacherService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    TeacherGroupMapper teacherGroupMapper;

    @Autowired
    DaoService daoService;

    @Override
    public ResultData<BasePageResp<TeacherGroupVO>> getTeacherGroupPage(TeacherGroupReq req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        req.setCaptainId(user.getId());
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<TeacherGroupVO> list = teacherGroupMapper.findAllPage(req);
        if(!CollectionUtils.isEmpty(list)){
            List<Long> memberIds = list.stream().map(TeacherGroupVO::getMemberId).collect(Collectors.toList());
            Map<Long, User> userMap = daoService.getUserMap(memberIds);
            list.stream().forEach(item->{
                item.setMemberAvatar(userMap.get(item.getMemberId()).getAvatar());
            });
        }
        return PageHelpUtil.buildPage(list,page);
    }
}
